package com.yifang.yibingproject.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yifang.yibingproject.entity.IpInfoEntity;
import com.yifang.yibingproject.entity.SysLogEntity;
import com.yifang.yibingproject.entity.SysUserEntity;
import com.yifang.yibingproject.mapper.SysLogMapper;
import com.yifang.yibingproject.query.LogPageQuery;
import com.yifang.yibingproject.service.IpInfoService;
import com.yifang.yibingproject.service.SysLogService;
import com.yifang.yibingproject.service.SysUserService;
import com.yifang.yibingproject.utils.LogConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class SysLogServiceImpl extends ServiceImpl<SysLogMapper, SysLogEntity> implements SysLogService {
    @Autowired
    private SysLogMapper sysLogMapper;


    @Autowired
    private SysUserService userService;

    @Autowired
    private IpInfoService ipInfoService;


    @Async("asyncExecutor")
    @Override
    public void add(SysLogEntity entity) {
        // 获取IP
        try {
            IpInfoEntity ipInfo = ipInfoService.getIpInfo(entity.getRequestIp());
            if (ipInfo != null) {
                entity.setAddress(String.join("", ipInfo.getCountry(), ipInfo.getProvince(), ipInfo.getCity()));
            }
        } catch (Exception e) {
            log.error("获取IP信息失败：" + e.getMessage(), e);
        }

        // 获取用户
        SysUserEntity user = userService.getById(entity.getUserId());
        if (user != null) {
            entity.setUsername(user.getUsername());
        } else {
           throw new RuntimeException("用户不存在");
        }

        // 保存操作记录
        save(entity);
    }

    @Override
    public void checkTableIfNotCreate() {
        String tableName = getCurrentTableName();
        List<String> tableNameList = sysLogMapper.selectTableNameList(tableName);
        if (tableNameList == null || !tableNameList.contains(tableName)) {
            // 创建日志表
            log.info("------------------创建日志表【" + tableName + "】----------------------");
            sysLogMapper.createTable(tableName);
            log.info("------------------创建日志表【" + tableName + "】成功------------------");
        }
    }

    @Override
    public Page<SysLogEntity> list(LogPageQuery query) {
        Page<SysLogEntity> page = new Page<>(query.getPageNo(), query.getPageSize());
        QueryWrapper<SysLogEntity> wrapper = new QueryWrapper<>();
        Optional.ofNullable(query.getRequestMethod()).filter(StringUtils::isNotBlank).ifPresent(m -> wrapper.eq("request_method", m));
        Optional.ofNullable(query.getUsername()).filter(StringUtils::isNotBlank).ifPresent(u -> wrapper.eq("username", u));
        Optional.ofNullable(query.getDescription()).filter(StringUtils::isNotBlank).ifPresent(d -> wrapper.eq("description", d));
        Optional.ofNullable(query.getRequestIp()).filter(StringUtils::isNotBlank).ifPresent(r -> wrapper.eq("request_ip", r));
        Optional.ofNullable(query.getAddress()).filter(StringUtils::isNotBlank).ifPresent(a -> wrapper.eq("address", a));
        wrapper.orderByDesc("create_time");
        page = page(page, wrapper);
        return page;
    }

    @Override
    public List<SysLogEntity> listByDate(String tableName, LocalDateTime start, LocalDateTime end) {
        return sysLogMapper.listByDate(tableName, start, end);
    }

    @Override
    public List<SysLogEntity> listByDateMember(String shopId, String tableName, LocalDateTime start, LocalDateTime end) {
        return sysLogMapper.listByDateMember(shopId, tableName, start, end);
    }

    private String getCurrentTableName() {
        // 默认访问本月的
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy_MM");
        return LogConst.TABLE_PREFIX + LocalDate.now().format(formatter);
    }
}
